BEGIN TRANSACTION
GO
DECLARE @ERR INT

--DELETE PREZZI WHERE codlist='OL0' and codtar in ('BS','MS','AS','B1','M1','A1')
	
PRINT 'inserisco i nuovi prezzi letti dal test'
INSERT INTO prezzi SELECT * FROM [192.168.50.146].Saremar2012TEST.dbo.prezzi 
	WHERE codlist='OL0' and codtar in ('BS','MS','AS','B1','M1','A1')

SELECT @ERR=@@ERROR
IF (@ERR <> 0)
	BEGIN
	GOTO ON_ERROR
	END


PRINT 'Inserisco le nuote tasse'
INSERT INTO configtasse select * from [192.168.50.146].Saremar2012TEST.dbo.configtasse 
	WHERE codlist='OL0' and codtar in ('BS','MS','AS','B1','M1','A1')

SELECT @ERR=@@ERROR
IF (@ERR <> 0)
	BEGIN
	GOTO ON_ERROR
	END
	
	
PRINT 'Inserisco le corse nella tab temporanea'
DECLARE @TMPCORSA TABLE (CODCORSA CHAR(16),ID_LINEA CHAR(14))
INSERT INTO @TMPCORSA SELECT CODCORSA, ID_LINEA FROM [192.168.50.146].Saremar2012TEST.dbo.corse 
	WHERE CODTRATTA IN ('CVOL','OLCV') AND DATAPART BETWEEN '2012-05-01 00:00:00' AND '2012-12-31 23:59:00'

SELECT @ERR=@@ERROR
IF (@ERR <> 0)
	BEGIN
	GOTO ON_ERROR
	END

PRINT 'Inserisco le limitazioni delle nuove corse'
INSERT INTO limitazioni SELECT * FROM [192.168.50.146].Saremar2012TEST.dbo.limitazioni 
	WHERE ID_LINEA IN (SELECT ID_LINEA FROM @TMPCORSA) AND COD_CFG_LINEA IN ('CVOL','OLCV')

SELECT @ERR=@@ERROR
IF (@ERR <> 0)
	BEGIN
	GOTO ON_ERROR
	END


PRINT 'Inserisco le nuove corse'
INSERT INTO CORSE SELECT * FROM [192.168.50.146].Saremar2012TEST.dbo.corse 
	WHERE CODTRATTA IN ('CVOL','OLCV') AND DATAPART BETWEEN '2012-05-01 00:00:00' AND '2012-12-31 23:59:00'

SELECT @ERR=@@ERROR
IF (@ERR <> 0)
	BEGIN
	GOTO ON_ERROR
	END
	
PRINT 'Inserisco la situazione delle nuove corse'
UPDATE PERSONALIZZAZIONI SET VALORE='0' WHERE CHIAVE='TRIGGERSITUAZIONE'
INSERT INTO situaz select * from [192.168.50.146].Saremar2012TEST.dbo.situaz 
	WHERE CODCORSA IN (SELECT CODCORSA FROM @TMPCORSA)
UPDATE PERSONALIZZAZIONI SET VALORE='1' WHERE CHIAVE='TRIGGERSITUAZIONE'

SELECT @ERR=@@ERROR
IF (@ERR <> 0)
	BEGIN
	GOTO ON_ERROR
	END
	
GOTO ON_SUCCESS


ON_ERROR:
		ROLLBACK TRANSACTION
		print 'fallito'

ON_SUCCESS:
	COMMIT TRANSACTION
	PRINT 'SUCCESSO'
